/**
 * 
 */
package per.lxy.wechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

import per.lxy.wechat.util.MyStringUtils;


/**
 * 网络辅助类
 * */
public class NetHelper {
	
	private static final int TASKLIST_PROCESS_INDEX = 1;
	
	private static final int NETSTAT_PROCESS_INDEX = 4;

	private static final int NETSTAT_HOSTINFO_INDEX = 2;

	
	/**
	 * 查找微信进程ID
	 * [8072, 10776]
	 * */
	public static Set<String> findWechatProcessName() throws IOException {
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("cmd.exe /c tasklist");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line = null;
		
		Set<String> processIds = new HashSet<>();
		while ((line = bufferedReader.readLine()) != null) {
			if(line.indexOf("WeChat") != -1) {
				processIds.add(MyStringUtils.extracTextInfo(line,TASKLIST_PROCESS_INDEX));
			}
		}
		return processIds;
	}
	/**
	 * 查找微信服务端ip和端口
	 * [14.17.43.152:80, 180.163.25.150:80]
	 * */
	public static Set<String> findWechatNet() throws IOException {
		
		Set<String> processIds = findWechatProcessName();
		
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("cmd.exe /c netstat -ano");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line = null;
		Set<String> hostinfoSet = new HashSet<>();
		while ((line = bufferedReader.readLine()) != null) {
			String processId = MyStringUtils.extracTextInfo(line,NETSTAT_PROCESS_INDEX);
			if(processIds.contains(processId)) {
				hostinfoSet.add(MyStringUtils.extracTextInfo(line,NETSTAT_HOSTINFO_INDEX));
			}
		}
		return hostinfoSet;
	}
	
	/**
	 * 查找微信服务端ip
	 * [14.17.43.152, 180.163.25.150]
	 * */
	public static Set<String> findWechatIp() throws IOException {
		Set<String> processIds = findWechatNet();
		return processIds.stream().map(id->{
			if(id!= null && id.indexOf(":")!=-1) {
				return id.split(":")[0];
			}
			return null;
		}).collect(Collectors.toSet());
	}
	

}